package com.dropesoft.biz;

import java.util.Date;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.dropesoft.entities.Training;

public class TrainingDbAdapter {


	private static final String DATABASE_TABLE = "allenamenti";
	
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DATA = "data";
    public static final String KEY_DESC= "descrizione";
    public static final String KEY_NOTE = "note";
    public static final String KEY_TOTALTIME = "tempo";
    public static final String KEY_DISTANCE = "distanza";
    public static final String KEY_AVGPACE = "passoMed";
    public static final String KEY_AVGSPEED = "velocitaMed";
    public static final String KEY_AVGBPM = "bpmMed";
    public static final String KEY_ENERGY = "colorie";
    public static final String KEY_UPDATEDATE = "dataAggiornamento";
    public static final String KEY_RESULT = "esito";
    public static final String KEY_USERID = "user_id";
    public static final String KEY_DISCIPLINEID = "discipline_id";
    
 
    private SQLiteDatabase _database;
    
    public void open() throws SQLException {
    	_database = _dbHelp.getWritableDatabase();
	}

	public void close() {
		_database.close();
	}
	
	private DbHelper _dbHelp;
	
	public TrainingDbAdapter(Context context)
	{
		_dbHelp = new DbHelper(context);
		
	}
	
	public Training createTraining(Training training)
	{
		
		ContentValues values = new ContentValues();	
		
		values.put(KEY_USERID, training.getUserId());
		values.put(KEY_DATA, Utility.IsoFormat.format(training.getData().getTime()));
		if(training.getDescrizione() != null) values.put(KEY_DESC, training.getDescrizione());
		if(training.getNote() != null) values.put(KEY_NOTE, training.getNote());
		values.put(KEY_TOTALTIME, training.getTempo());
		values.put(KEY_DISTANCE, training.getDistanza());
		values.put(KEY_AVGPACE, training.getPassoMed());
		values.put(KEY_AVGSPEED, training.getVelocitaMed());
		values.put(KEY_AVGBPM, training.getBpmMed());
		values.put(KEY_ENERGY, training.getCalorie());
		values.put(KEY_UPDATEDATE, Utility.IsoFormat.format(training.getDataAggiornamento().getTime()));
		values.put(KEY_RESULT, training.getEsito());
		values.put(KEY_DISCIPLINEID, training.getIdDiscipline());
		
		int id = (int) _database.insert(DATABASE_TABLE, null, values);
		
		training.setId(id);
		
		return training;
		
	}
	
	public Training updateTraining(Training training)
	{
		ContentValues values = new ContentValues();
		
		values.put(KEY_USERID, training.getUserId());
		values.put(KEY_DATA, Utility.IsoFormat.format(training.getData().getTime()));
		if(training.getDescrizione() != null) values.put(KEY_DESC, training.getDescrizione());
		if(training.getNote() != null) values.put(KEY_NOTE, training.getNote());
		values.put(KEY_TOTALTIME, training.getTempo());
		values.put(KEY_DISTANCE, training.getDistanza());
		values.put(KEY_AVGPACE, training.getPassoMed());
		values.put(KEY_AVGSPEED, training.getVelocitaMed());
		values.put(KEY_AVGBPM, training.getBpmMed());
		values.put(KEY_ENERGY, training.getCalorie());
		values.put(KEY_UPDATEDATE, Utility.IsoFormat.format(training.getDataAggiornamento()));
		values.put(KEY_RESULT, training.getEsito());
		values.put(KEY_DISCIPLINEID, training.getIdDiscipline());
		
		String whereClause = KEY_ROWID +" = ?";
		String[] whereArgs = { String.valueOf(training.getId()) };
		
		int id = (int) _database.update(DATABASE_TABLE, values, whereClause, whereArgs);
		
		training.setId(id);
		return training;
	}
	
	// Ritorna tutti gli allenamenti
	public Cursor listAllTraining()  throws SQLException 
	{
		Cursor cursor = _database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID,
             	KEY_USERID,
             	KEY_DATA,
             	KEY_DESC,
             	KEY_NOTE,
             	KEY_TOTALTIME,
             	KEY_DISTANCE,
             	KEY_AVGPACE,
             	KEY_AVGSPEED,
             	KEY_AVGBPM,
             	KEY_ENERGY,
             	KEY_UPDATEDATE,
             	KEY_RESULT,
             	KEY_DISCIPLINEID}, null, null,
             null, null, KEY_DATA, null);
		return cursor;
	}
	// Seleziona gli allenamenti di un determinato mese
	public Cursor listMonthTraining(String month)  throws SQLException 
	{
		Cursor cursor = _database.query(true, DATABASE_TABLE, new String[] {
				KEY_ROWID,
             	KEY_USERID,
             	KEY_DATA,
             	KEY_DESC,
             	KEY_NOTE,
             	KEY_TOTALTIME,
             	KEY_DISTANCE,
             	KEY_AVGPACE,
             	KEY_AVGSPEED,
             	KEY_AVGBPM,
             	KEY_ENERGY,
             	KEY_UPDATEDATE,
             	KEY_RESULT,
             	KEY_DISCIPLINEID}, "strftime('%m', "+ KEY_DATA +")"  + "='" + month + "'", null,
             null, null, KEY_DATA, null);
		return cursor;
	}
	
	public Training getTraining(long trainingId)
	{
		
		Training trainig = new Training();
		Cursor cursor = _database.query(true, DATABASE_TABLE, new String[] {
					KEY_ROWID,
                 	KEY_USERID,
                 	KEY_DATA,
                 	KEY_DESC,
                 	KEY_NOTE,
                 	KEY_TOTALTIME,
                 	KEY_DISTANCE,
                 	KEY_AVGPACE,
                 	KEY_AVGSPEED,
                 	KEY_AVGBPM,
                 	KEY_ENERGY,
                 	KEY_UPDATEDATE,
                 	KEY_RESULT,
                 	KEY_DISCIPLINEID}, KEY_ROWID + "=" + trainingId, null,
                 null, null, null, null);
		
		if(cursor.moveToNext())
		{
			Date data = null;
			
			try {
				
				data =  Utility.IsoFormat.parse(cursor.getString(2));
				trainig.setData(data);
				
				//data = Utility.IsoFormat.parse(cursor.getString(11));
				//trainig.setDataAggiornamento(new GregorianCalendar(data.getYear(), data.getMonth(), data.getDay(), data.getHours(), data.getMinutes(), data.getSeconds()));
				
			} catch (Exception e) {
				// TODO: handle exception
				//msg = e.getMessage();
			}
			if(!cursor.isNull(3)) trainig.setDescrizione(cursor.getString(3));
			if(!cursor.isNull(4)) trainig.setNote(cursor.getString(4));
			if(!cursor.isNull(5)) trainig.setTempo(cursor.getFloat(5));
			if(!cursor.isNull(6)) trainig.setDistanza(cursor.getFloat(6));
			if(!cursor.isNull(7)) trainig.setPassoMed(cursor.getFloat(7));
			if(!cursor.isNull(8)) trainig.setVelocitaMed(cursor.getFloat(8));
			if(!cursor.isNull(9)) trainig.setBpmMed(cursor.getInt(9));
			if(!cursor.isNull(10)) trainig.setCalorie(cursor.getInt(10));
			if(!cursor.isNull(12)) trainig.setEsito(cursor.getInt(12));
			if(!cursor.isNull(13)) trainig.setIdDiscipline(cursor.getInt(13));
		}
		cursor.close();
		return trainig;
	}
	public void deleteTraining(long id)
	{
		String whereClause = KEY_ROWID + " = ?";
		String[] whereArgs = { String.valueOf(id) };
		
		_database.delete(DATABASE_TABLE, whereClause, whereArgs);
	}
}
